# This Python file uses the following encoding: utf-8

# if __name__ == "__main__":
#     pass
#!/usr/bin/env python3

import subprocess
import os
import pty
import socket
import select
import argparse
import subprocess
import time
import shutil

class LaserScanRos2():

    def __init__(self) -> None:
        self.laser_pro = None


class SocketServer():
    def __init__(self,lport=8889,uart_name="/tmp/fishbot_laser") -> None:
        self.lport = lport
        self.uart_name = uart_name
        self.laser_ros2 = LaserScanRos2()
        self.main()

    def main(self):
        s = None
        master = None
        slave = None
        print(".py is running")
        try:
            # 创建 socket
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind(('0.0.0.0', self.lport))
            s.listen(5)
            print("socket create successful")

            # 创建 PTY
            master, slave = pty.openpty()
            if os.path.exists(self.uart_name):
                os.remove(self.uart_name)
            os.symlink(os.ttyname(slave), self.uart_name)
            print(f"UART2SOCKET:{self.lport}->{self.uart_name}")

            # 创建 poll 对象
            mypoll = select.poll()
            mypoll.register(master, select.POLLIN)

            while True:
                print("Prepare to Accept connect!")
                client, client_address = s.accept()
                mypoll.register(client.fileno(), select.POLLIN)
                print(s.fileno(), client, master)
                print('PTY: Opened {} for {}:{}'.format(
                    os.ttyname(slave), '0.0.0.0', self.lport))
                is_connect = True

                try:
                    while is_connect:
                        fdlist = mypoll.poll(256)
                        for fd, event in fdlist:
                            try:
                                data = os.read(fd, 256)
                                if len(data) == 0:
                                    is_connect = False
                                    break
                                write_fd = client.fileno() if fd == master else master
                                os.write(write_fd, data)
                            except (ConnectionResetError, OSError) as e:
                                print(f"Error reading/writing data: {e}")
                                is_connect = False
                                break
                except Exception as e:
                    print(f"Unexpected error: {e}")
                finally:
                    # 关闭客户端连接并注销
                    mypoll.unregister(client.fileno())
                    client.close()
                    print("Client disconnected and resources released.")
        except Exception as e:
            print(f"Server error: {e}")
        finally:
            # 确保所有资源被释放
            if s:
                s.close()
            if master:
                os.close(master)
            if slave:
                os.close(slave)
            if os.path.exists(self.uart_name):
                os.remove(self.uart_name)
            print("Server closed and all resources released.")

def main():
    print("into main")
    # 清理旧资源
    if os.path.exists("/tmp/fishbot_laser"):
        os.remove("/tmp/fishbot_laser")
    SocketServer()
    print("socket enbance")


if __name__ == "__main__":
    print("into _main_")
    main()

